/*
 	Bleetbox Chrome Extension 2
	Mat Ryer
 */
var BbXhr;

var BbXhr_StateChange = function(){
	
	if (BbXhr.readyState == 4) {
		
		var res = JSON.parse(BbXhr.responseText);
  	var tabId = parseInt(res.c);

		if (res.w == true) {
			
			if (res.d[0].bltrs == 0) {
			
				var messages = res.d[0].msgs;
				chrome.browserAction.setTitle({ tabId: tabId, title: "There are " + messages + " message(s) on this page - click to read them and join in" });
				chrome.browserAction.setBadgeBackgroundColor({ tabId: tabId, color: [255, 0, 0, 128] });
				chrome.browserAction.setBadgeText({ tabId: tabId, text: ""+messages});
		
			} else {
				
				var bleeters = res.d[0].bltrs;
				chrome.browserAction.setTitle({ tabId: tabId, title: "There are " + bleeters + " people on this page now - click to join in" });
				chrome.browserAction.setBadgeBackgroundColor({ tabId: tabId, color: [0, 128, 0, 255] });
				chrome.browserAction.setBadgeText({ tabId: tabId, text: ""+bleeters});
			
			}
		} else {
			chrome.browserAction.setBadgeText({ tabId: tabId, text: ""});
		}
		
	}
	
};

var Bb_StartGettingSiteInfo = function(url, tabId){
	
	chrome.browserAction.setBadgeText({text: ""});
	
	BbXhr = new XMLHttpRequest();
	BbXhr.onreadystatechange = BbXhr_StateChange;
	BbXhr.open("GET", "http://bleetbox.com/locations/summary.json?c=" + tabId + "&url=" + encodeURI(url), true);
	BbXhr.send();
	
};

var Bb_Tabs_onNewPage = function(url, tabId){
	
	// if this is NOT bleetbox...
	if (url.indexOf("http://bleetbox.com") == -1) {
		// user has moved page
		Bb_StartGettingSiteInfo(url, tabId);	
	}
	
};

var Bb_Tabs_onUpdated = function(tabId, changes, tab){
	if (changes.status == "complete") {
		Bb_Tabs_onNewPage(tab.url, tabId);
	}
};

// bind to the Chrome events
chrome.browserAction.onClicked.addListener(function() {
	chrome.tabs.executeScript(null, {file: "bleet-about-this-page.js"});
});

chrome.tabs.onUpdated.addListener(Bb_Tabs_onUpdated);
